package com.sport.service.Impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sport.config.security.service.userDetailServiceImpl;
import com.sport.entity.SysRole;
import com.sport.entity.SysUser;
import com.sport.mapper.SysUserMapper;
import com.sport.utils.*;
import com.sport.service.SysUserService;
import com.sport.vo.LoginVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class SysUserServiceImpl implements SysUserService {
    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private userDetailServiceImpl userDetailsService;

    @Autowired
    private PasswordEncoder passwordEncoder;
    @Value("${jwt.tokenHead}")
    private  String tokenHead;

    @Autowired
    TokenUtil tokenUtil;
    @Override
    public Result login(LoginVo loginVo) {
       log.info("1.开始登录");
      UserDetails userDetails= userDetailsService.loadUserByUsername(loginVo.getUsername());
        System.out.println("登录接口中的用户信息"+userDetails);
        System.out.println("获取用户信息中的角色权限信息"+userDetails.getAuthorities());
     log.info("2.判断");
      if(null==userDetails||passwordEncoder.matches((MD5Utils.md5(loginVo.getPassword())),userDetails.getPassword())){
        return Result.fail("账号或密码错误，请重新输入");
      }

        if(!userDetails.isEnabled()){
            return Result.fail("该账号被禁用，请联系管理员");
        }
        log.info("登录成功,在security对象中存入登陆者信息");
        UsernamePasswordAuthenticationToken authenticationToken=new UsernamePasswordAuthenticationToken(userDetails,null,userDetails.getAuthorities());
        System.out.println(authenticationToken);
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        log.info("根据登录信息获取token");
        //需要借助jwt生成token;
        String token=tokenUtil.generateToken(userDetails);
        System.out.println("token-=====》==="+token);
        Map<String,String > map=new HashMap<>();
        map.put("tokenHead",tokenHead);
        map.put("token",token);
        System.out.println("+token-=====》==="+map.get(token)+"tokenHead===="+map.get(tokenHead));
        return Result.success("登录成功!",map);
    }

    @Override
    public SysUser findByUsername(String username) {
        return sysUserMapper.findByUsername(username);
    }

    @Override
    public Result findPage(QueryInfo queryInfo) {
        log.info("开始权限分页:--->页面{},--->页数{},查询内容{}",queryInfo.getPageNumber(),queryInfo.getPageSize(),queryInfo.getQueryString());
        System.out.println(queryInfo);
        PageHelper.startPage(queryInfo.getPageNumber(), queryInfo.getPageSize());
        Page<SysUser> page = sysUserMapper.findPage(queryInfo.getQueryString());
        long total=page.getTotal();
        List<SysUser> result=page.getResult();

        result.forEach(item-> {
            item.setRoles(sysUserMapper.findRoles(item.getId()));
//            item.setName(item.getUsername());

        });
        return PageResult.pageResult(total,result);


    }
@Transactional
    @Override
    public Result insert(SysUser user) {
        log.info("根据用户名查询是否存在角色");

        SysUser user1=sysUserMapper.findByUsername(user.getUsername());

        if(null!=user1){
            return Result.fail("该用户已经存在");
        }
        user.setPassword(passwordEncoder.encode(MD5Utils.md5(user.getPassword())));
        sysUserMapper.insert(user);
        log.info("添加角色信息");
        List<SysRole> roles=user.getRoles();
        if(roles.size()>0){
              roles.forEach(item->sysUserMapper.insertUserRole(user.getId(),item.getId()));
            }
        log.info("用户添加成功,该用户共有{}个角色",roles.size());


        return Result.success("添加用户成功");
    }

    @Override
    public Result delete(long id) {
        SysUser user=sysUserMapper.findById(id);
        if(null==user){
            return Result.fail("用户ID不存在");
        }
        sysUserMapper.deleteRolesByUserId(id);
       sysUserMapper.delete(id);
        return Result.success("用户删除成功");

    }

    @Override
    public Result update(SysUser user) {
    log.info("1、先将用户角色信息给删除");
    sysUserMapper.deleteRolesByUserId(user.getId());

    log.info("2、添加用户角色信息");
    List<SysRole> roles=user.getRoles();
    if(roles.size()>0)
        roles.forEach(item->{
            sysUserMapper.insertUserRole(user.getId(),item.getId());
        });
        user.setPassword(passwordEncoder.encode(MD5Utils.md5(user.getPassword())));
    log.info("3、用户修改成功");
    sysUserMapper.update(user);
    return Result.success("用户修改信息成功");
    }

    @Override
    public void updatePwdByMail(String email, String password) {
        log.info("修改密码");
        sysUserMapper.updatePwdByMail(email,password);
    }


}
